import 'package:flutter/material.dart';

import '../../utils/util.dart';
import 'dialog.dart';
import 'index.dart';

class SelectionController extends GetxController {
  final GlobalKey titleKey = GlobalKey();
  Function(SelectionResultModel res)? complete;
  void Function(SelectionResultModel res)? onChanged;
  SelectionModel? mod;
  @override
  void onInit() {
    super.onInit();
    if (mod?.list == null || mod?.list?.isEmpty == true) {
      return;
    }
    for (var e1 in mod!.list!) {
      if (e1.isSelected) {
        e1.isSelected = true;
        e1.isShow = true;
        return;
      }
      if (e1.list?.isNotEmpty == true) {
        for (var e2 in e1.list!) {
          if (e2.isSelected) {
            e1.isShow = true;
            return;
          }
          if (e2.list?.isNotEmpty == true) {
            for (var e3 in e2.list!) {
              if (e3.isSelected) {
                e1.isShow = true;
                return;
              }
            }
          }
        }
      }
    }
  }

  void onDataChanged(SelectionModel md) {
    update();
    if (onChanged != null) {
      var res = valueChanged(md);
      onChanged!(res);
    }
  }

  void actionTitle({
    required int index,
    required SelectionModel md,
    Function(SelectionResultModel res)? complete,
  }) {
    this.complete = complete;

    showSelectionDialog(key: titleKey, md: md, controller: this);
  }

  void actionChooseDate({
    required SelectionModel md,
    SelectionModel? parent,
  }) {
    showCalendar(
      isRange: true,
      result: (start, end) {
        var beginTimeStr =
            DateFormat.format(start!, DateFormatType.ymd, dateSeprator: '-');

        var endTimeStr =
            DateFormat.format(end!, DateFormatType.ymd, dateSeprator: '-');
        Get.log("$beginTimeStr,$endTimeStr");
        md.text = "发布时间";
        md.val = "$beginTimeStr,$endTimeStr";
        if (parent?.list != null) {
          for (var i = 0; i < parent!.list!.length; i++) {
            var e = parent.list![i];
            if (e.tag == md.relateTag) {
              e.list?.forEach((e2) {
                e2.isSelected = false;
              });
            }
          }
        }

        onDataChanged(md);
      },
    );
  }

  void actionItem({
    required SelectionModel md,
    SelectionModel? parent,
  }) {
    if (md.itemStyle == SelectionItemStyle.date) {
      actionChooseDate(md: md, parent: parent);
      return;
    }
    if (parent?.tag != 0 || parent?.relateTag != null) {
      mod?.list?.forEach((e) {
        if (e.relateTag == parent?.tag || parent?.tag == e.tag) {
          e.list?.forEach((e2) {
            e2.isSelected = false;
            e2.val = '';
          });
          e.val = '';
        }
      });
    }

    if (parent == null) {
      return;
    }

    if (md.list == null) {
      ///点击全部或者最后一列选项
      md.isShow = true;
      md.isSelected = !md.isSelected;
    } else {
      if (!md.isShow) {
        md.isShow = true;
      } else {
        md.isSelected = true;
      }
    }

    if (mod?.list?.have((p0) => p0.text == md.text) != true) {
      // 无论是否选中都只需设置当前点击项的最父层为展示
      if (md.list == null) {
        ///全部

        //最末端只需要设置第一层
        mod?.list?.forEach((e1) {
          if (e1.text == parent.text) {
            e1.isShow = true;
            if (parent.list?.have((p0) => !p0.isSelected) == true) {
              ///同级队列中有未选中
              parent.isSelected = false;
            } else {
              parent.isSelected = true;
              if (e1.list?.have((p0) => !p0.isSelected) == true) {
                ///父级队列中有未选中
                e1.isSelected = false;
              } else {
                e1.isSelected = true;
              }
            }
          } else {
            e1.isShow = false;
            if (md.isSelected && !parent.isMutiable) {
              e1.isSelected = false;
            }
          }
        });
      } else {
        //第二层选中
        parent.isShow = true;
        if (md.isSelected) {
          parent.list?.forEach((e1) {
            if (!parent.isMutiable) {
              e1.isSelected = e1.text == md.text && md.isSelected;
            }
          });
          parent.isSelected =
              !(parent.list?.have((p0) => !p0.isSelected) == true);
        }
        mod?.list?.forEach((e1) {
          e1.isShow = e1.text == parent.text;
        });
      }
    } else {
      ///第一层
      if (!parent.isMutiable && md.isSelected) {
        mod?.list?.forEach((e1) {
          e1.isShow = e1.text == md.text;
          e1.isSelected = e1.text == md.text && md.isSelected;
        });
      }
      mod?.list?.forEach((e1) {
        e1.isShow = e1.text == md.text;
      });
    }

    // parent.isSelected =
    //     parent.list?.where((element) => element.isSelected == false).isEmpty ??
    //         false;
    Get.log('${md.isSelected ? '选中' : '取消'}---${md.text}');
    onDataChanged(mod!);
  }

  void actionReset(SelectionModel md) {
    md.isSelected = false;
    md.list?.forEach((e1) {
      e1.isSelected = false;
      e1.val = '';
      e1.list?.forEach((e2) {
        e2.isSelected = false;
        e2.val = '';
      });
    });
    onDataChanged(md);
  }

  void actionSure(SelectionModel md) {
    var res = valueChanged(md);
    if (complete != null) {
      complete!(res);
    }
    dismissSelection();
  }

  SelectionResultModel valueChanged(SelectionModel md) {
    List<String> val = [];
    List<SelectionResultModel> items = [];

    if (md.list != null) {
      int? relateTag;
      for (var e1 in md.list!) {
        if (e1.itemStyle == SelectionItemStyle.date ||
            e1.itemStyle == SelectionItemStyle.input ||
            e1.itemStyle == SelectionItemStyle.custom) {
          if (e1.val.isNotEmpty) {
            items.add(
              SelectionResultModel(key: e1.title ?? e1.text, val: e1.val),
            );
            if (e1.relateTag != null) {
              relateTag = e1.relateTag;
            }
          }
          continue;
        }
        if (e1.tag == relateTag) {
          continue;
        }
        if (e1.text == '全部' && e1.isSelected) {
          val.add(e1.text);
          break;
        }

        var l = e1.list?.where((element) => element.isSelected);

        if (l == null || l.isEmpty == true) {
          if (e1.isSelected) {
            val.add(e1.text);
            items.add(
              SelectionResultModel(key: e1.title ?? e1.text, val: e1.text),
            );
          }
        } else {
          md.text = e1.text;
          for (var e2 in l) {
            val.add(e2.text);
            items.add(
              SelectionResultModel(key: e2.title ?? e2.text, val: e2.text),
            );
          }
        }
      }
    }

    var res = SelectionResultModel(
      key: md.text,
      val: val.join(','),
      items: items,
    );
    return res;
  }

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }
}
